/**
 * 骑乘收益
 * gf
 */

import { PageWrapper } from "@/components/PageWrapper";
import CusDatePicker from "@/components/Picker/datePicker";
import { Title } from "@/components/Title";
import { useState, useEffect } from "react";
import styled from "styled-components";
import { FlexDiv } from "@/components/FOF/DoubleInput";
import { Text } from "@/components/FOF/SelectInput";
import SSelect from "@/components/Select";
import { collectErrors } from "@/components/FOF/InlineInput";
import { Select, Table } from "antd";
import SInputNumber from "@/components/Input/InputNumber";
import dayjs from 'dayjs';
import styles from "./index.less";
import { RedBtn } from "@/components/Button";
import cn from "classnames";
import * as _ from "lodash";
import CustomizeRadio from "@/components/CustomizeRadio";
import GraphOrTable from "@/components/CustomizeRadio/graphOrTable";
import { get_ride_earnings_list, query_graph } from "./service";
import MultiLine from "@/components/EchartsComponents/Line/MultiLine";
import { getBaseColors, getExpandColors } from "@/utils/echarts";
import { get_last_trading_date } from "@/service/global";

export const RidingHeader = styled.div`
  display: flex;
  min-width: 1068px;
  padding: 8px 12px;
  border: 1px solid #e4e4e4;
  margin-top: 12px;
`;
const RidingBody = styled.div`
  border: 1px solid #e4e4e4;
  margin-top: 12px;
  text-align: center;
`;
export const NewText = styled(Text)`
  opacity: 0.7;
  margin-left: 24px;
  font-weight: 600;
`;

const TableTitle = ({line1, line2}) => {
  return (
    <div className={styles.tableTitle}>
      <div>{line1}</div>
      <div>{line2}</div>
    </div>
  );
};

const renderPercent = (text) => {
  return _.isNumber(text) ? text + "%" : "-";
};

const RidingColumns = [
  {
    title: "期限(年)",
    dataIndex: "timeLimit",
    key: "timeLimit",
    width: 44,
    align: "center",
    render: (text) => <span style={{ fontWeight: "600" }}>{text}</span>,
  },
  {
    title: <TableTitle line1="综合收益率" line2="(静态假设)" />,
    dataIndex: "staticYieldRate",
    key: "staticYieldRate",
    width: 92,
    render: (text) => renderPercent(text),
  },
  {
    title: "到期收益率",
    dataIndex: "yieldToMaturity",
    key: "yieldToMaturity",
    width: 92,
    render: (text) => renderPercent(text),
  },
  {
    title: "卖出收益率",
    dataIndex: "sellingRate",
    key: "sellingRate",
    width: 92,
    render: (text) => renderPercent(text),
  },
  {
    title: <TableTitle line1="综合收益率" line2="（假设上行10BP）" />,
    dataIndex: "overallYieldRate",
    key: "overallYieldRate",
    width: 92,
    render: (text) => renderPercent(text),
  },
  {
    title: <TableTitle line1="盈亏平衡利差" line2="(右轴)" />,
    dataIndex: "breakEvenSpread",
    key: "breakEvenSpread",
    width: 92,
    render: (text) => (_.isNumber(text) ? text : "-"),
  },
  {
    title: "底线覆盖利差",
    dataIndex: "bottomLineCoverageSpread",
    key: "bottomLineCoverageSpread",
    ellipsis:true,
    width: 92,
    render: (text) => (_.isNumber(text) ? text : "-"),
  },
  {
    title:<TableTitle line1="情景1" line2="上行5BP" />,
    dataIndex: "upFiveBP",
    key: "upFiveBP",
    width: 92,
    render: (text) => renderPercent(text),
  },
  {
    title: <TableTitle line1="情景2" line2="上行10BP" />,
    dataIndex: "upTenBP",
    key: "upTenBP",
    width: 92,
    render: (text) => renderPercent(text),
  },
  {
    title: <TableTitle line1="情景3" line2="上行15BP" />,
    dataIndex: "upFifteenBP",
    key: "upFifteenBP",
    width: 92,
    render: (text) => renderPercent(text),
  },
  {
    title: <TableTitle line1="情景4" line2="上行20BP" />,
    dataIndex: "upTwentyBP",
    key: "upTwentyBP",
    width: 92,
    render: (text) => renderPercent(text),
  },
  {
    title: <TableTitle line1="情景5" line2="上行30BP" />,
    dataIndex: "upThirtyBP",
    key: "upThirtyBP",
    width: 92,
    render: (text) => renderPercent(text),
  },
];
const RidingReturns = () => {
  const [start, setStart] = useState(dayjs(Date.now()));
  const [errorList, setErrorList] = useState<string[]>([]);
  const [isChanged, setIsChanged] = useState(false);
  const [displayType, setDisplayType] = useState("graph");
  const [loadingQuery, setLoadingQuery] = useState(false);
  const [lineData, setLineData] = useState({});
  const [yData, setYData] = useState([]);
  const [saveParams, setSaveParams] = useState({
    endDate: dayjs(Date.now()).format("YYYY-MM-DD"),
    lineType: "1",
    holdTime: 0.25,
    bottomLine: 1,
    assumeUp: 10,
  });
  const [columns, setColumns] = useState(RidingColumns);
  const [list, setList] = useState([]);

  // 查询列表
  const handleQueryList = (date?: string) => {
    setLoadingQuery(true);
    get_ride_earnings_list({
      ...saveParams,
      endDate: date || dayjs(start).format("YYYY-MM-DD"),
      holdTime: Number(saveParams.holdTime),
      bottomLine: Number(saveParams.bottomLine),
      assumeUp: Number(saveParams.assumeUp),
    }).then((res) => {
      setLoadingQuery(false);
      if (res?.code === "0") {
        setList(res?.data || []);
        const r = columns.map((v) => {
          if (v.key === "overallYieldRate") {
            v.title = <TableTitle line1="综合收益率" line2={`（假设上行${saveParams.assumeUp}BP）`} />;
          }
          return v;
        });
        setColumns(r);
      }
    });
  };

  // 查询chart
  const handleQueryChart = (date?: string) => {
    setLoadingQuery(true);
    query_graph({
      ...saveParams,
      endDate: date || dayjs(start).format("YYYY-MM-DD"),
      holdTime: Number(saveParams.holdTime),
      bottomLine: Number(saveParams.bottomLine),
      assumeUp: Number(saveParams.assumeUp),
    }).then((res) => {
      setLoadingQuery(false);
      let b = [];
      if (res?.code === "0") {
        if (res.data.yaxis) {
          res.data.yaxis.map((v) => {
            if (v.value) {
              v.value.map((m) => {
                m.key = m.key.toFixed(1).toString();
              });
            }
          });
          const a = [
            "盈亏平衡利差(右轴)",
            "到期收益率",
            "综合收益率（静态假设）",
            `综合收益率（情景假设：上行${saveParams.assumeUp}BP）`,
          ];
          const cData = res.data.yaxis;
          const i_0 = _.findIndex(cData, (v) => v.label === a[0]);
          const i_1 = _.findIndex(cData, (v) => v.label === a[1]);
          const i_2 = _.findIndex(cData, (v) => v.label === a[2]);
          const i_3 = _.findIndex(cData, (v) => v.label === a[3]);
          b = [cData[i_0], cData[i_1], cData[i_2], cData[i_3]];
        }
        setLineData(res.data);
        setYData(b);
      }
    });
  };

  useEffect(() => {
    get_last_trading_date({}).then((res) => {
      if (res?.code === "0") {
        setStart(dayjs(res.data));
        handleQueryChart(res.data);
        handleQueryList(res.data);
      }
    });
  }, []);

  // 保存查询条件
  const handleSaveParams = (e: any) => {
    setStart(e);
    setIsChanged(true);
    setSaveParams((state) => {
      return {
        ...state,
        endDate: dayjs(e).format("YYYY-MM-DD"),
      };
    });
  };

  const onChange = (val: string, key: string) => {
    handleCollectErrors(val?.toString(), key);
    setIsChanged(true);
    setSaveParams((state) => {
      return {
        ...state,
        [key]: val || "",
      };
    });
  };

  // 收集错误
  const handleCollectErrors = (val?: string, key?: string) => {
    let res: string[] = collectErrors(val, key, errorList, saveParams);
    setErrorList(res);
    return [res];
  };

  const onClick = () => {
    let errL: string[] = [];
    for (let i of Object.keys(saveParams)) {
      if (!saveParams[i]) {
        errL.push(i);
      }
    }
    if (errL.length > 0) {
      setErrorList(errL);
      return;
    } else {
      handleQueryList();
      handleQueryChart();
    }
  };

  const tableClass = (arr: any, max?: number) =>
    cn({
      [styles.scrollTable]: true,
      hidden: arr?.length < 8,
      [styles.scrollTableFix]: max && arr?.length > max,
      [styles.empty]: _.isEmpty(arr),
      [styles.ridingTable]: true,
    });

  // const list = new Array(40).fill('').map((v) => {
  //   return {
  //     year: 1.0,
  //   }
  // })

  const changeDisplayType = (e) => {
    setDisplayType(e);
  };
  return (
    <PageWrapper narrow minWidth="1068px" className={styles.ridingpage}>
      <Title style={{marginLeft: 16}}>骑乘收益</Title>
      <RidingHeader>
        <CusDatePicker
          label="时间范围"
          startValue={start}
          single={true}
          idName1="riding-date"
          onChange={handleSaveParams}
          className={styles.customDatePicker}
          disabledDate={(currentDate: any) => {
            return (
              dayjs(currentDate).startOf("days").valueOf() >
              dayjs(Date.now()).valueOf()
            );
          }}
        />
        <FlexDiv>
          <NewText style={{ marginRight: 8 }}>标的曲线</NewText>
          <SSelect
            suffixIcon={<div className="findfit_icon_arrow " />}
            value={saveParams.lineType}
            onChange={(e) => onChange(e, "lineType")}
            iserror={errorList.includes("lineType")}
            style={{ width: 134 }}
          >
            {/* {selectList?.map((v) => (
              <Select.Option key={v.benchmarkCode} value={v.benchmarkCode}>
                {v.benchmarkName}
              </Select.Option>
            ))} */}
            <Select.Option key={"1"} value={"1"}>
              中债国开曲线
            </Select.Option>
          </SSelect>
        </FlexDiv>
        <FlexDiv>
          <NewText>持有时间</NewText>
          <SInputNumber
            value={saveParams.holdTime}
            min={0}
            max={1000}
            precision={2}
            onChange={(e: any) => onChange(e, "holdTime")}
            isError={errorList.includes("holdTime")}
            suffix="年"
          />
        </FlexDiv>
        <FlexDiv>
          <NewText>底线收益</NewText>
          <SInputNumber
            value={saveParams.bottomLine}
            min={-10000}
            max={10000}
            precision={2}
            onChange={(e: any) => onChange(e, "bottomLine")}
            isError={errorList.includes("bottomLine")}
            suffix="%"
          />
        </FlexDiv>
        <FlexDiv>
          <NewText>假设上行</NewText>
          <SInputNumber
            value={saveParams.assumeUp}
            min={-10000}
            max={10000}
            precision={0}
            onChange={(e: any) => onChange(e, "assumeUp")}
            isError={errorList.includes("assumeUp")}
            suffix="BP"
          />
        </FlexDiv>
        <RedBtn
          style={{ marginLeft: 12, marginTop: 3 }}
          disabled={!isChanged}
          onClick={!isChanged ? null : onClick}
          loading={loadingQuery}
        >
          开始计算
        </RedBtn>
      </RidingHeader>
      <RidingBody>
        <div className={styles.chartHead}>
          <span>骑乘收益（{dayjs(start).format("YYYY/MM/DD")}）</span>
          <GraphOrTable value={displayType} setValue={changeDisplayType} />
        </div>
        {displayType === "graph" ? (
          <div style={{ height: 440, textAlign: "center" }}>
            <MultiLine
              idName="riding-asset"
              // xAxis={lineData?.xaxis?.map(v => parseFloat(v)) || []}
              xAxis={lineData?.xaxis}
              // legend={lineData?.yaxis?.map((v) => v.label)}
              legend={yData?.map((v) => v.label)}
              data={yData || []}
              color={["#A4B2C4", "#3457C4", "#40A6DF", "#E85C36"]}
              rightY={["盈亏平衡利差(右轴)"]}
              areaName={["盈亏平衡利差(右轴)"]}
              xAxisLabelProps={{
                rotate: -90,
              }}
              yAxisLabelProps={{
                color: "#35425e",
                opacity: 0.7,
                fontSize: 10,
                margin: 8,
                verticalAlign: "bottom",
                formatter: (value, index) => {
                  return value.toFixed(2);
                },
              }}
              gridStyle={{
                top: 40,
                bottom: 0,
                left: 12,
                right: 6,
              }}
              xAxisProps={{
                splitLine: {
                  show: true,
                  lineStyle: {
                    type: "dashed",
                    color: "#EDF0F5",
                  },
                },
              }}
              leftYName={{
                name: "年化收益率(%)",
                nameTextStyle: {
                  fontSize: 10,
                  color: "#35425e",
                  opacity: 0.7,
                },
              }}
              rightYName={{
                name: "利差(BP)",
                nameTextStyle: {
                  fontSize: 10,
                  color: "#35425e",
                  opacity: 0.7,
                },
              }}
              toolTipTitle="剩余期限（年）："
            />
          </div>
        ) : (
          <Table
            className={tableClass(list, 7)}
            columns={RidingColumns}
            // rowKey={(r) => r.id + r.provinceCode}
            dataSource={list}
            bordered
            scroll={{ y: document.body.offsetHeight - 200 }}
            pagination={false}
          />
        )}
        {displayType === "graph" && (
          <span
            style={{
              color: "#35425E",
              fontSize: 12,
              transform: "scale(0.83)",
              opacity: 0.7,
              display: "inline-block",
              position: "relative",
              top: "-4px",
            }}
          >
            剩余期限(年)
          </span>
        )}
      </RidingBody>
    </PageWrapper>
  );
};

export default RidingReturns;
